package com.jrx.anytxn.transaction.job.paph.step;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.config.PaphFileConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author liuyu
 * @Description 银行扣款结果监听
 */
@Service
public class GenerateRepayDetailFileListener implements JobExecutionListener {

	private static final Logger logger = LoggerFactory.getLogger(GenerateRepayDetailFileListener.class);

	@Autowired
	private IOrganizationTableService organizationTableService;
	@Autowired
	private PaphFileConfig paphFileConfig;

	@Override
	public void beforeJob(JobExecution jobExecution) {
		this.checkFile(Constant.PRODECUT_TYPE_JY);
		this.checkFile(Constant.PRODECUT_TYPE_XF);
	}

	@Override
	public void afterJob(JobExecution jobExecution) {

	}

	private void checkFile(String productType) {
		String detailFilePath = paphFileConfig.getRepayDetailFilePath();
		String fileType = paphFileConfig.getFileType();

		PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
		String nextProcessDate = DateUtils.format(org.getNextProcessingDate(), "yyyyMMdd");
		String fileName =
				Constant.LS_BANK + productType + "_" + nextProcessDate + "_" + TransBizConstant.PREPAY_DETAIL + "_" + fileType + ".txt";

		String filePath = detailFilePath + org.getTenantId() + File.separator + nextProcessDate + File.separator + productType + File.separator;

		Path detailFile = Paths.get(filePath + fileName);
		Path pFile = Paths.get(filePath);

		if (!Files.exists(detailFile)) {
			//判断文件夹是否存在
			if (!Files.isDirectory(pFile)) {
				//创建文件夹
				try {
					Files.createDirectories(pFile);
				} catch (IOException e) {
					logger.error("创建目录失败", e);
					throw new RuntimeException(e);
				}
			}
		} else {
			// 文件存在则删除
			try {
				Files.delete(detailFile);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}

		//创建文件
		try {
			Files.createFile(detailFile);
		} catch (IOException e) {
			logger.error("创建文件失败", e);
			throw new RuntimeException(e);
		}
	}
}
